<template>
  <view class="ai-chat-page">
    <!-- 顶部标题栏 -->
    <view class="chat-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content">
        <view class="header-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="header-title">🤖 AI智能助手</text>
        <view class="header-right" @click="clearChat">
          <text class="clear-icon">🗑️</text>
        </view>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y 
      :scroll-top="scrollTop"
      scroll-with-animation>
      
      <!-- 欢迎消息 -->
      <view class="message-item assistant-message" v-if="messages.length === 0">
        <view class="avatar">
          <text class="avatar-icon">🤖</text>
        </view>
        <view class="message-content">
          <view class="message-bubble">
            <text class="message-text">您好！我是黄山旅游智能助手，很高兴为您服务！\n\n我可以帮您解答关于：\n• 黄山景点介绍\n• 登山路线规划\n• 陪爬服务咨询\n• 安全注意事项\n\n请随时提问！</text>
          </view>
        </view>
      </view>

      <!-- 消息列表 -->
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        class="message-item"
        :class="msg.role === 'user' ? 'user-message' : 'assistant-message'">
        
        <view class="avatar" v-if="msg.role === 'assistant'">
          <text class="avatar-icon">🤖</text>
        </view>
        
        <view class="message-content">
          <view class="message-bubble" :class="msg.role === 'user' ? 'user-bubble' : 'assistant-bubble'">
            <text class="message-text">{{ msg.content }}</text>
          </view>
          <text class="message-time">{{ formatTime(msg.time) }}</text>
        </view>
        
        <view class="avatar" v-if="msg.role === 'user'">
          <text class="avatar-icon">👤</text>
        </view>
      </view>

      <!-- 加载中提示 -->
      <view class="message-item assistant-message" v-if="isLoading">
        <view class="avatar">
          <text class="avatar-icon">🤖</text>
        </view>
        <view class="message-content">
          <view class="message-bubble">
            <view class="typing-indicator">
              <text class="dot"></text>
              <text class="dot"></text>
              <text class="dot"></text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="chat-input-area">
      <view class="input-wrapper">
        <textarea 
          class="input-box"
          v-model="inputMessage"
          placeholder="请输入您的问题..."
          :auto-height="true"
          :maxlength="500"
          @confirm="sendMessage"
        />
        <button 
          class="send-btn"
          :class="{ 'send-btn-active': inputMessage.trim() }"
          :disabled="isLoading || !inputMessage.trim()"
          @click="sendMessage">
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      scrollTop: 0,
      currentTypingIndex: 0,
      typingInterval: null,
      statusBarHeight: 0 // 状态栏高度
    }
  },
  
  // 页面加载时获取状态栏高度
  onLoad() {
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight || 0
    console.log('状态栏高度:', this.statusBarHeight)
  },
  
  // 页面卸载时清理定时器
  onUnload() {
    if (this.typingInterval) {
      clearInterval(this.typingInterval)
      this.typingInterval = null
    }
  },
  
  methods: {
    // 发送消息
    async sendMessage() {
      const message = this.inputMessage.trim()
      if (!message || this.isLoading) return
      
      // 添加用户消息
      this.messages.push({
        role: 'user',
        content: message,
        time: new Date()
      })
      
      // 清空输入框
      this.inputMessage = ''
      
      // 滚动到底部
      this.scrollToBottom()
      
      // 添加"思考中"的占位消息
      this.messages.push({
        role: 'assistant',
        content: '正在思考中...',
        time: new Date()
      })
      
      // 显示加载状态
      this.isLoading = true
      
      try {
        // 直接调用火山引擎API
        await this.callVolcengineAPI()
        
      } catch (error) {
        console.error('AI聊天失败', error)
        
        // 替换最后一条消息为错误提示
        this.messages[this.messages.length - 1] = {
          role: 'assistant',
          content: '抱歉，服务暂时不可用，请稍后再试。\n错误信息：' + (error.message || '未知错误'),
          time: new Date()
        }
        
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        this.scrollToBottom()
      }
    },
    
    // 直接调用火山引擎API
    async callVolcengineAPI() {
      // 构建消息列表（包含系统提示词和历史对话）
      const messagesList = [
        {
          role: 'system',
          content: '你是黄山旅游的智能助手，专门为游客提供黄山旅游相关的咨询服务。你可以回答关于黄山景点、登山路线、陪爬服务、安全注意事项等问题。请用友好、专业的语气回答用户的问题。'
        },
        ...this.messages
          .filter(msg => msg.role !== 'system' && msg.content !== '正在思考中...')
          .slice(-10) // 只保留最近10条对话作为上下文
          .map(msg => ({
            role: msg.role,
            content: msg.content
          }))
      ]
      
      // 构建请求数据
      const requestData = {
        model: 'doubao-seed-1-6-251015',
        messages: messagesList
      }
      
      console.log('发送请求到火山引擎:', requestData)
      
      // 发送请求
      const response = await uni.request({
        url: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
		  // 第三方密钥
		  
          'Authorization': 'Bearer 7501-3040-4-acb6-4cf7e8ec8ssdfdsf61'
        },
        data: requestData
      })
      
      const [error, res] = response
      
      if (error) {
        console.error('请求失败:', error)
        throw new Error('网络请求失败')
      }
      
      console.log('收到响应:', res)
      
      if (res.statusCode === 200) {
        const aiReply = res.data.choices[0].message.content
        console.log('AI回复:', aiReply)
        
        // 使用打字机效果显示回复
        this.typewriterEffect(aiReply)
      } else {
        throw new Error(res.data.error?.message || '请求失败')
      }
    },
    
    // 打字机效果
    typewriterEffect(fullContent) {
      // 清除之前的定时器
      if (this.typingInterval) {
        clearInterval(this.typingInterval)
      }
      
      this.currentTypingIndex = 0
      const lastMessageIndex = this.messages.length - 1
      
      // 初始化为空内容
      this.messages[lastMessageIndex].content = ''
      
      // 逐字显示
      this.typingInterval = setInterval(() => {
        if (this.currentTypingIndex < fullContent.length) {
          this.messages[lastMessageIndex].content += fullContent.charAt(this.currentTypingIndex)
          this.currentTypingIndex++
          
          // 强制更新视图
          this.$forceUpdate()
          
          // 滚动到底部
          this.scrollToBottom()
        } else {
          // 打字完成
          clearInterval(this.typingInterval)
          this.typingInterval = null
          this.currentTypingIndex = 0
        }
      }, 50) // 每50ms显示一个字符
    },
    
    // 清空聊天记录
    clearChat() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有聊天记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.messages = []
            uni.showToast({
              title: '已清空',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 返回首页
    goBack() {
      uni.reLaunch({
        url: '/pages/index',
        fail: (err) => {
          console.error('返回首页失败', err)
          // 如果reLaunch失败，尝试navigateBack
          uni.navigateBack({
            fail: () => {
              uni.showToast({
                title: '返回失败',
                icon: 'none'
              })
            }
          })
        }
      })
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 99999
      })
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
.ai-chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 顶部标题栏 */
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  position: relative;
}

.header-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
}

.header-left,
.header-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.header-left:active,
.header-right:active {
  opacity: 0.7;
}

.back-icon,
.clear-icon {
  font-size: 40rpx;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
}

.user-message {
  flex-direction: row-reverse;
}

.assistant-message {
  flex-direction: row;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.avatar-icon {
  font-size: 44rpx;
}

.message-content {
  max-width: 70%;
  margin: 0 20rpx;
}

.message-bubble {
  padding: 20rpx;
  border-radius: 16rpx;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.user-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.assistant-bubble {
  background: #fff;
  color: #333;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.message-text {
  font-size: 28rpx;
  line-height: 1.6;
}

.message-time {
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
  display: block;
}

/* 输入中动画 */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #667eea;
  animation: typing 1.4s infinite;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.3;
  }
  30% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}

/* 输入区域 */
.chat-input-area {
  background: #fff;
  border-top: 1rpx solid #eee;
  padding: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 20rpx;
}

.input-box {
  flex: 1;
  min-height: 80rpx;
  max-height: 200rpx;
  background: #f5f7fa;
  border-radius: 20rpx;
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.5;
}

.send-btn {
  width: 120rpx;
  height: 80rpx;
  background: #ddd;
  color: #999;
  border-radius: 20rpx;
  font-size: 28rpx;
  border: none;
  transition: all 0.3s;
}

.send-btn-active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.send-btn::after {
  border: none;
}
</style>

